package svgedit.gui.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import svgedit.gui.Frame;
import svgedit.gui.SVGFileFilter;

/** Shows a file dialog for the user to select a new file to write the document
 *  to, then saves it at that location.
 */
@SuppressWarnings("serial")
public class SaveDocumentAsAction extends AbstractAction {

	private Frame frame;

	/** Create this action for the given frame */
	public SaveDocumentAsAction(Frame frame) {
		super("Save As...");
		this.frame = frame;
	}

	public void actionPerformed(ActionEvent arg0) {
		File file = frame.getDocument().getFile();
		JFileChooser dialog;
		if (file != null)
			dialog = new JFileChooser(file);
		else
			dialog = new JFileChooser(frame.getPreferences().getDefaultPath());
		dialog.addChoosableFileFilter(new SVGFileFilter());
		dialog.showSaveDialog(null);

		file = dialog.getSelectedFile();
		if (file.getName().toLowerCase().endsWith(".svgz")) {
			if (file != null) {
				if (file.exists()) {
					if (JOptionPane.showConfirmDialog(frame.getRootPane(),
							String.format("Do you want to replace the existing file named %s?",
									file.getName()), "Overwrite existing file?",
									JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION)
						return;
				}
				frame.getPreferences().setDefaultPath(file.getPath());
				
				// Create a temporary file to export it to svgz
				frame.saveFile(new File (".\\temp.svg"));
				File temp = new File(".\\temp.svg");
				frame.saveSVGZ(file,temp);
			}

		}
		else {
			if (file != null) {
				if (file.exists()) {
					if (JOptionPane.showConfirmDialog(frame.getRootPane(),
							String.format("Do you want to replace the existing file named %s?",
									file.getName()), "Overwrite existing file?",
									JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION)
						return;
				}
				frame.getPreferences().setDefaultPath(file.getPath());
				frame.saveFile(file);
			}
		}
	}

}
